﻿using System;
using VideoStore.Business.Facade;
using VideoStore.Common.Response;
using VideoStore.Common.Response.Extension;
using VideoStore.Services.Dto;
using VideoStore.Services.Interface;
using VideoStore.Services.Translation;
using VideoStore.Services.Translation.Base;
using VideoStore.Services.Translation.Factory;

namespace VideoStore.Services
{
    public class WarehouseService : IWarehouseService
    {
        #region Implementation of IWarehouseService

        /// <summary>
        /// Gets the warehouse by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Response<WarehouseDto> GetWarehouseById(int id)
        {
            var response = new Response<WarehouseDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoStoreFacade.Instance;
                Domain.Entities.Warehouse warehouse = facade.GetWarehouseById(id);
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(WarehouseTranslator));
                response.ResponseObject = translator.TranslateToDto<Domain.Entities.Warehouse, WarehouseDto>(warehouse);
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.AddFatalError(ex.Message);
            }
            return response;
        }

        /// <summary>
        /// Creates the warehouse.
        /// </summary>
        /// <param name="newWarehouse">The new warehouse.</param>
        /// <returns></returns>
        public Response<WarehouseDto> CreateWarehouse(WarehouseDto newWarehouse)
        {
            var response = new Response<WarehouseDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoStoreFacade.Instance;
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(WarehouseTranslator));
                Domain.Entities.Warehouse warehouseEntity = translator.TranslateToEntity<WarehouseDto, Domain.Entities.Warehouse>(newWarehouse);
                Domain.Entities.Warehouse savedWarehouse = facade.CreateWarehouse(warehouseEntity);
                response.ResponseObject = translator.TranslateToDto<Domain.Entities.Warehouse, WarehouseDto>(savedWarehouse);
                response.Messages.AddSuccessfulSaveMessage("Warehouse");
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.AddFatalError(ex.Message);
            }
            return response;
        }

        #endregion
    }
}